package org.loofer.uiframework.navigator.backstack;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;

public abstract class AbstractFragment extends Fragment {
    public static final int FRAGMENT_LAUNCH_CLEAR_TOP = 1;
    public static final int FRAGMENT_LAUNCH_SINGLE_TOP = 4;
    public static final int FRAGMENT_LAUNCH_UNHIDE = 2;
    private FragmentBackHelper mFragmentBackHelper = new FragmentBackHelper(this);
    private int mLaunchFlag;
    int mRequestCode = -1;
    int mResultCode = 0;
    Intent mResultData;

    public FragmentBackHelper getFragmentBackHelper() {
        return this.mFragmentBackHelper;
    }

    public void setRequestCode(int requestCode) {
        this.mRequestCode = requestCode;
    }

    protected boolean isSingleTop() {
        return (this.mLaunchFlag & 4) != 0;
    }

    public boolean isClearTop() {
        return (this.mLaunchFlag & 1) != 0;
    }

    public boolean isHiddenPreviousFragment() {
        return (this.mLaunchFlag & 2) == 0;
    }

    public void setLaunchFragmentFlag(int launchFlag) {
        this.mLaunchFlag = launchFlag;
    }

    public final void launchFragment(AbstractFragment fragment) {
        this.mRequestCode = -1;
        this.mFragmentBackHelper.launchFragment(fragment);
    }

    public final void launchFragmentForResult(AbstractFragment fragment, int requestCode) {
        this.mRequestCode = requestCode;
        this.mFragmentBackHelper.launchFragment(fragment);
    }

    protected void onNewBundle(Bundle bundle) {
    }

    public void onNewPause() {
    }

    public void onNewResume() {
    }

    public void finish() {
        FragmentBackStackManager parentFragmentBackStackManager = getFragmentBackHelper().getParentFragmentBackStackManager();
        if (parentFragmentBackStackManager == null) {
            return;
        }
        if (parentFragmentBackStackManager.isRootFragment(this)) {
            getActivity().finish();
        } else {
            parentFragmentBackStackManager.destroyFragment(this);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

    public boolean onBackPressed() {
        return getFragmentBackHelper().onBackPressed();
    }

    public final void setResult(int resultCode) {
        setResult(resultCode, null);
    }

    public final void setResult(int resultCode, Intent data) {
        this.mResultCode = resultCode;
        this.mResultData = data;
        FragmentActivity activity = getActivity();
        if (activity != null) {
            activity.setResult(resultCode, data);
        }
    }
}
